import { loadEnv } from 'vite';
import { resolve } from 'path';
import WindiCSS from 'vite-plugin-windicss';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import { createSvgIconsPlugin } from 'vite-plugin-sutpc-svg-icons';
import vitePluginSutpcLibStaticImport from 'vite-plugin-sutpc-lib-static-import';
import vitePluginSutpcLessDeep from 'vite-plugin-sutpc-less-deep';
import vitePluginPurgeIcons from 'vite-plugin-purge-icons';
import vitePluginSutpcIconPark from 'vite-plugin-sutpc-icon-park';
import vitePluginSutpcCommon from 'vite-plugin-sutpc-common';
import vitePluginSutpcPublicPath from './vite-plugin-sutpc-public-path';
import viteCompression from 'vite-plugin-compression';
import rollupPluginVisualizer from 'rollup-plugin-visualizer';
import { createHtmlPlugin } from 'vite-plugin-html';
import { ViteEjsPlugin } from 'vite-plugin-ejs'
import externalGlobals from 'rollup-plugin-external-globals';

import type { UserConfig, ConfigEnv } from 'vite';

const root = process.cwd();
const pathResolve = (dir: string) => resolve(root, '.', dir);

export default ({ command, mode }: ConfigEnv): UserConfig => {
  const isBuild = command === 'build';
  const argMode = process.argv[3] === '--mode' ? process.argv[4] : process.argv[3];
  const configDir = pathResolve('config');
  const env = loadEnv(isBuild ? mode : argMode, configDir);
  const publicPath = env.VITE_APP_MODE === 'LIB' ? `/bizapp/${env.VITE_APP_KEY}/front/` : '/'; // env.VITE_APP_STATIC_PROXY;
  // const publicPath = `/bizapp/${import.meta.env.VITE_APP_KEY}/front`;
  const buildOptions =
    env.VITE_APP_MODE === 'LIB'
      ? {
          // 库模式定制
          outDir: env.VITE_OUT_DIR + '/' + env.VITE_APP_KEY,
          lib: {
            entry: resolve('src/lib.ts'),
            name: env.VITE_APP_KEY,
            fileName: 'lib'
          }
        }
      : {
          // 正常模式
          outDir: env.VITE_OUT_DIR || 'dist'
        };
  return {
    envDir: pathResolve('config'),
    base: env.VITE_BASE_PATH,
    plugins: [
      vue(),
      vueJsx(),
      vitePluginSutpcLibStaticImport(),
      vitePluginSutpcLessDeep(),
      vitePluginSutpcCommon({
        noOnlineIconify: true
      }),
      vitePluginPurgeIcons(),
      vitePluginSutpcIconPark(),
      vitePluginSutpcPublicPath(publicPath),
      createSvgIconsPlugin(),
      WindiCSS(),
      ViteEjsPlugin({
        title: env.VITE_APP_TITLE
      }),
      viteCompression({
        threshold: 1024 * 2, // 对大于 2kb 的文件进行压缩
        filter: /.(js|mjs|json|css|html|geojson)$/i,
        disable: false //是否禁用压缩，默认为 false
      })
      // isBuild &&
      //   rollupPluginVisualizer({
      //     emitFile: true, //是否被触摸
      //     filename: 'analyze.html', //生成分析网页文件名
      //     open: true, //在默认用户代理中打开生成的文件
      //     gzipSize: true, //从源代码中收集 gzip 大小并将其显示在图表中
      //     brotliSize: true //从源代码中收集 brotli 大小并将其显示在图表中
      //   })
    ],
    define: {
      'process.env': {}
    },
    resolve: {
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.less', '.css'],
      alias: [
        // {
        //   find: 'vue-i18n',
        //   replacement: 'vue-i18n/dist/vue-i18n.cjs.js'
        // },
        {
          find: /\@\//,
          replacement: `${pathResolve('src')}/`
        }
      ]
    },
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
          globalVars: {
            publicPath: publicPath
          }
        }
      }
    },
    build: {
      ...buildOptions,
      rollupOptions: {
        // 确保外部化处理那些你不想打包进库的依赖
        external: env.VITE_APP_MODE === 'LIB' ? ['vue', 'vue-router', 'pinia', 'echarts'] : [],
        output: {
          // 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
          globals: {
            vue: 'Vue',
            'vue-router': 'VueRouter',
            pinia: 'Pinia',
            echarts: 'echarts',
            'element-plus': 'ElementPlus'
          }
        },
        plugins: [
          env.VITE_APP_MODE === 'LIB'
            ? externalGlobals({
                vue: 'Vue',
                'vue-router': 'VueRouter',
                pinia: 'Pinia',
                echarts: 'echarts',
                'element-plus': 'ElementPlus',
                'vue-i18n': 'VueI18n'
                // '@sutpc/axios': 'request'
              })
            : null
        ]
      },
      sourcemap: env.VITE_SOURCEMAP === 'true' ? 'inline' : false,
      reportCompressedSize: false,
      chunkSizeWarningLimit: 2000,
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_debugger: env.VITE_DROP_DEBUGGER === 'true',
          drop_console: env.VITE_DROP_CONSOLE === 'true'
        }
      }
    },
    server: {
      host: '0.0.0.0',
      proxy: {
        [env.VITE_TESPBASE_PATH]: {
          target: env.VITE_TESP_API_BASEPATH,
          changeOrigin: true
          // rewrite: path => path.replace(/^\/web\/tespbiz-prjlib/, '')
        },
        [env.VITE_FILE_PROXY]: {
          target: `http://10.3.4.149:9000`,
          changeOrigin: true,
          rewrite: (path) => path.replace(new RegExp('^' + env.VITE_FILE_PROXY + ''), '')
        },
        ['/bizapp/' + env.VITE_APP_KEY + '/api/']: {
          target: `http://10.3.4.193:9601`,
          changeOrigin: true,
          rewrite: (path) => path.replace(new RegExp('^/bizapp/' + env.VITE_APP_KEY + '/api'), '')
        },
        ['/portal/api/']: {
          target: `http://10.3.4.193:10000`,
          changeOrigin: true,
          rewrite: (path) => path.replace(new RegExp('^/portal/api'), '')
        },
        ['/tiannetST/']: {
          // target: `http://172.16.0.198:12085/api/ps-show`,
          target: `http://111.160.76.111:10000/api/ps-show`,
          changeOrigin: true,
          rewrite: (path) => path.replace(new RegExp('^/tiannetST/'), '')
        }
      }
    },
    optimizeDeps: {
      include: [
        'vue',
        'vue-router',
        'lodash-es',
        'element-plus/es/locale/lang/zh-cn',
        'element-plus/es/locale/lang/en',
        '@iconify/iconify',
        '@sutpc/zebra',
        '@sutpc/vue3-ec-resize',
        'axios',
        'qs',
        'echarts',
        'vue-i18n'
      ]
    }
  };
};
